//
//  TagListViewController.m
//  iFlickr
//
//  Created by 张 霄鹤 on 09-8-22.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "TagListViewController.h"
#import "DataManager.h"
#import "ViewControllerChooser.h"


@implementation TagListViewController

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/


- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.navigationItem.title = NSLocalizedStringFromTable(@"TAG",@"main",@"");

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	
	hotTags = [[NSMutableArray alloc] init];
	// TODO 启动线程，装载flickr中的Top10
	loading = NO;
	active = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
	
	CGFloat w = self.view.frame.size.width;
	CGFloat h = self.view.frame.size.height;
	
	CGFloat sw = active.frame.size.width;
	CGFloat sh = active.frame.size.height;
	
	CGFloat sx = (w - sw)/2;
	CGFloat sy = (h - sh)/2 - 50;
	
	[active setFrame:CGRectMake(sx, sy, sw, sh)];
	[self startLoad];
}

/**
 * 开启线程，进行下载，显示 UIActiveIndicatorView
 */
-(void)startLoad{
	if(loading == NO){
		[self.view addSubview:active];
		[active startAnimating];
		[NSThread detachNewThreadSelector:@selector(loadHotTags:) toTarget:self withObject:nil];
		loading = YES;
	}
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1; // 两个section 一个是 用户自己的，一个是 Hot Tag, 目前只针对Hot 做
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [hotTags count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
#ifndef __IPHONE_3_0
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
#else
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
#endif
	}
    
    // Set up the cell...
	
	NSInteger row = indexPath.row;
	
	NSString *cellTitle = [hotTags objectAtIndex:row];
#ifdef __IPHONE_3_0
		cell.textLabel.text = cellTitle;
#else
		cell.text = cellTitle;
#endif
	
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	
	[self.view addSubview:active];
	[active startAnimating];
	
	NSInteger row = indexPath.row;
	NSString *tag = (NSString *)[hotTags objectAtIndex:row];
	[NSThread detachNewThreadSelector:@selector(loadPhotos:) toTarget:self withObject:tag];
	
	[tableView deselectRowAtIndexPath:indexPath animated:NO];

}

/**
 * 表头标题
 */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
	NSString *ret = nil;
	if(section == 0){
		ret = @"Top10";
	}
	return ret;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/**
 * 重新装载表单，此方法由线程调用主线程执行
 */
-(void)reloadTable:(id)sender{
	[self.tableView reloadData];
}

/**
 * 开启线程，进行标签下载
 */
-(void)loadHotTags:(id)sender{
	// 装载 hot Tag
	DataManager *dm = [DataManager sharedDataManager];
	NSArray *tags = [dm getHotTag:10];
	BOOL loadOK = NO;
	if(tags){
		int cc = [tags count];
		if(cc > 0){
			[hotTags setArray:tags];
			loadOK = YES;
		}
	}
	[active stopAnimating];
	[active removeFromSuperview];
	if(loadOK){
		[self performSelectorOnMainThread:@selector(reloadTable:) withObject:nil waitUntilDone:NO];
	}
	loading = NO;
}

/**
 * 点击表格进行图片加载
 * sender 作为参数，这个参数是 NSString 类型，标签名称
 */
-(void)loadPhotos:(id)sender{
	if(loading == NO){
		loading = YES;
		DataManager *dm = [DataManager sharedDataManager];
		NSMutableDictionary *params = [dm initParams];
		[params setObject:sender forKey:@"tags"];
		[params setObject:@"url_sq" forKey:@"extras"];      // 增加针对 75x75 图像URL的获取
		[params setObject:@"10" forKey:@"per_page"];
		NSArray *photos = [dm searchPhoto:params];
		[active stopAnimating];
		[active removeFromSuperview];
		// 不论是否执行正确，先停止进度显示，然后进行
		if(photos){
			// TODO 如果是 photos 内部的元素的属性为 nil 那么会抛异常
			// NSLog(@"%@",photos);
			//PhotoListViewController *next = (PhotoListViewController *)[[ViewControllerChooser sharedChooser] choose:VCC_ID_PHOTOLIST];
//			[next resetImage];
//			next.title = (NSString *)sender;
//			[next loadPhotoList:photos];
//			[self.navigationController pushViewController:next animated:YES];
		}else {
			// TODO Error
		}
		
		loading = NO;
	}
}


- (void)dealloc {
	[hotTags release];
	[active release];
    [super dealloc];
}


@end

